<template>

  <el-dialog
    top="20px"
    :title="defaultValue.title"
    :lock-scroll="defaultValue.lockScroll"
    :append-to-body="tableConfig.appendToBody"
    :visible="tableConfig.show"
    @close="tableConfig.show = false"
    :show-close="tableConfig.showClose"
    :destroy-on-close="tableConfig.destroyOnClose"
    width="1100px">

    <!-- 批量操作工具栏 -->
    <div style="margin-bottom: 10px;">
      <el-button type="primary" size="mini" @click="toggleAllSelection">
        {{ isAllSelected ? '取消全选' : '全选' }}
      </el-button>
      <el-button type="success" size="mini" @click="batchImport" :loading="importLoading">
        批量导入 ({{ selectedSoftware.length }})
      </el-button>
      <span style="margin-left: 10px; color: #909399; font-size: 12px;">
        共 {{ currComputerSoftware.length }} 个可导入软件
      </span>
    </div>

    <!-- 软件列表表格 -->
    <el-table
      ref="multipleTable"
      :data="currComputerSoftware"
      style="width: 100%"
      max-height="500"
      @selection-change="handleSelectionChange"
      v-loading="tableLoading">

      <el-table-column type="selection" width="55"></el-table-column>

      <el-table-column prop="name" label="软件名称" min-width="150" show-overflow-tooltip>
      </el-table-column>

      <el-table-column prop="describe" label="描述" min-width="120" show-overflow-tooltip>
      </el-table-column>

      <el-table-column prop="app" label="运行平台" width="100">
        <template slot-scope="scope">
          {{ appToChinese(scope.row.app) }}
        </template>
      </el-table-column>

      <el-table-column prop="typeId" label="软件类型" width="150">
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.typeId"
            size="mini"
            placeholder="选择类型"
            style="width: 100%">
            <el-option
              v-for="item in softwareTypeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="grade" label="评分" width="180">
        <template slot-scope="scope">
          <el-rate
            v-model="scope.row.grade"
            :texts="texts"
            show-text
            size="small">
          </el-rate>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="80" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="singleImport(scope.row)">
            导入
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 导入结果统计 -->
    <div v-if="importResult" style="margin-top: 15px; padding: 10px; background: #f5f7fa; border-radius: 4px;">
      <div style="color: #67C23A; margin-bottom: 5px;">
        ✓ 成功: {{ importResult.success }} 个
      </div>
      <div v-if="importResult.fail > 0" style="color: #F56C6C;">
        ✗ 失败: {{ importResult.fail }} 个
        <el-button type="text" size="mini" @click="showFailList = true">查看详情</el-button>
      </div>
    </div>

    <!-- 失败详情对话框 -->
    <el-dialog
      title="导入失败详情"
      :visible.sync="showFailList"
      width="600px"
      append-to-body>
      <el-table :data="failList" size="small">
        <el-table-column prop="name" label="软件名称"></el-table-column>
        <el-table-column prop="error" label="失败原因" show-overflow-tooltip></el-table-column>
      </el-table>
    </el-dialog>

    <span slot="footer" class="dialog-footer">
      <el-button plain type="warning" @click="batchImport" :loading="importLoading">
        批量导入 ({{ selectedSoftware.length }})
      </el-button>
      <el-button plain type="primary" @click="tableConfig.show = false">关闭</el-button>
    </span>

  </el-dialog>

</template>

<script>
import http from '@/utils/http'

export default {
  name: "CurrComputerSoftware",
  components: {},
  data() {
    return {
      // 软件类型
      softwareTypeList: [],
      // 当前可以导入的软件
      currComputerSoftware: [],
      // 选中的软件
      selectedSoftware: [],
      // 是否全选
      isAllSelected: false,
      // 表格加载状态
      tableLoading: false,
      // 导入加载状态
      importLoading: false,
      // 导入结果
      importResult: null,
      // 失败列表
      failList: [],
      // 显示失败详情
      showFailList: false,
      // 评价文字说明
      texts: ['非常差', '较差', '一般', '优秀', '经典'],
      // 表格的默认值
      tableConfig: {
        // 关闭时销毁 Dialog 中的元素
        destroyOnClose: true,
        // 弹出框是否打开
        show: false,
        // 是否显示关闭按钮
        showClose: true,
        // 下面2个属性解决打开弹出框后没有在最上面显示的问题，导致看到的内容是一半的，需要先将滚动条移到最上面
        lockScroll: false,
        appendToBody: true,
      },
      // 默认值，进入页面后的值
      defaultValue: {
        // 弹出框标题
        title: '导入软件',
        // 保存还是修改or查看,取值有 select | save | upd
        saveUpdSelect: 'save'
      },
    }
  },
  methods: {
    /**
     * 运行平台转中文
     */
    appToChinese(item) {
      const map = {
        1: "手机",
        2: "小程序",
        3: "Windows",
        4: "苹果",
        5: "Linux",
        9: "其他"
      }
      return map[item] || "其他"
    },

    /**
     * 处理选中变化
     */
    handleSelectionChange(selection) {
      this.selectedSoftware = selection
      this.isAllSelected = selection.length === this.currComputerSoftware.length
    },

    /**
     * 全选/取消全选
     */
    toggleAllSelection() {
      if (this.isAllSelected) {
        this.$refs.multipleTable.clearSelection()
      } else {
        this.currComputerSoftware.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      }
      this.isAllSelected = !this.isAllSelected
    },

    /**
     * 单个导入
     */
    async singleImport(software) {
      try {
        this.importLoading = true
        const result = await this.importSoftware(software)
        if (result.success) {
          this.$message.success(`软件"${software.name}"导入成功`)
          // 从列表中移除已导入的软件
          this.removeImportedSoftware(software)
        } else {
          this.$message.error(`软件"${software.name}"导入失败: ${result.error}`)
        }
      } catch (error) {
        this.$message.error(`导入失败: ${error.message}`)
      } finally {
        this.importLoading = false
      }
    },

    /**
     * 批量导入
     */
    async batchImport() {
      if (this.selectedSoftware.length === 0) {
        this.$message.warning('请选择要导入的软件')
        return
      }

      this.importLoading = true
      this.importResult = null

      try {
        const results = []
        const failList = []

        // 逐个导入选中的软件
        for (const software of this.selectedSoftware) {
          const result = await this.importSoftware(software)
          results.push(result)
          if (!result.success) {
            failList.push({
              name: software.name,
              error: result.error
            })
          }
        }

        const successCount = results.filter(r => r.success).length
        const failCount = results.length - successCount

        this.importResult = {
          success: successCount,
          fail: failCount
        }
        this.failList = failList

        if (failCount === 0) {
          this.$message.success(`成功导入 ${successCount} 个软件`)
        } else {
          this.$message.warning(`导入完成: 成功 ${successCount} 个, 失败 ${failCount} 个`)
        }

        // 从列表中移除已成功导入的软件
        this.selectedSoftware.forEach(software => {
          const result = results.find(r => r.software === software)
          if (result && result.success) {
            this.removeImportedSoftware(software)
          }
        })

        // 清空选择
        this.selectedSoftware = []
        this.isAllSelected = false

        this.$emit('getSoftwareListPage', null)
        // 关闭弹出框
        this.tableConfig.show = false

      } catch (error) {
        this.$message.error(`批量导入失败: ${error.message}`)
      } finally {
        this.importLoading = false
      }
    },

    /**
     * 从列表中移除已导入的软件
     */
    removeImportedSoftware(software) {
      const index = this.currComputerSoftware.findIndex(item => item === software)
      if (index > -1) {
        this.currComputerSoftware.splice(index, 1)
      }
    },

    /**
     * 导入单个软件
     */
    importSoftware(software) {
      return new Promise((resolve) => {
        // 直接使用接口返回的数据，不需要额外处理
        const importData = {
          name: software.name,
          app: software.app,
          inUse: software.inUse,
          typeId: software.typeId,
          grade: software.grade,
          localSaveAddress: software.localSaveAddress,
          officialAddress: software.officialAddress,
          describe: software.describe,
          remarks: software.remarks
        }

        http.post("/software/saveSoftware", importData).then(response => {
          let res = response.data
          if (res.status === 'success') {
            resolve({ success: true, data: res.data, software: software })
          } else {
            resolve({ success: false, error: res.msg || '导入失败', software: software })
          }
        }).catch(error => {
          resolve({ success: false, error: error.message || '网络错误', software: software })
        })
      })
    },

    /**
     * 打开弹出框之前
     * @param type 软件类型
     */
    openCurrComputerSoftware(type) {
      // 从外部转入，减少查询
      this.softwareTypeList = type
      this.resetDialog()
      this.getCurrComputerSoftware()

      this.tableConfig.show = true
      this.$store.commit('navigationListChange', ['导入软件', this.defaultValue.title])
    },

    /**
     * 重置对话框状态
     */
    resetDialog() {
      this.selectedSoftware = []
      this.isAllSelected = false
      this.importResult = null
      this.failList = []
      this.showFailList = false
    },

    /**
     * 获取当前计算机软件列表
     */
    getCurrComputerSoftware() {
      this.tableLoading = true
      http.post("/software/getCurrComputerSoftware", {}).then(response => {
        let res = response.data
        if (res.status === 'error') {
          if (res.code !== 401) {
            this.$message.error(res.msg)
          }
          return
        }

        if (res.data) {
          // 直接使用接口返回的数据
          this.currComputerSoftware = res.data
        } else {
          this.currComputerSoftware = []
        }

      }).catch(error => {
        this.$message.error(error.message)
        this.currComputerSoftware = []
      }).finally(() => {
        this.tableLoading = false
      })
    }
  },
  watch: {
    'tableConfig.show': function(newVal) {
      if (!newVal) {
        // 对话框关闭时重置状态
        this.resetDialog()
      }
    }
  }
}

</script>

<style scoped>
</style>
